﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Shell;

using GrimorioApplication.Localization;
using GrimorioApplication.Model;
using System.IO.IsolatedStorage;

namespace GrimorioApplication.Views
{
    public partial class AddRecipePivot : PhoneApplicationPage
    {
        PhotoChooserTask photoChooserTask = new PhotoChooserTask();

        string photoNameOfRecipe = "";

        public AddRecipePivot()
        {
            InitializeComponent();
            ApplicationBarInitializer();
            AddTemporaryRecipe();
            this.photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_completed);
            recipeDishListPicker.ItemsSource = new List<string> { 
                GrimorioLang.listpicker_dish_antipasto, 
                GrimorioLang.listpicker_dish_primo,
                GrimorioLang.listpicker_dish_secondo,
                GrimorioLang.listpicker_dish_contorno,
                GrimorioLang.listpicker_dish_dolce };

            recipeDifficultyListPicker.ItemsSource = new List<string>
            {
                GrimorioLang.listpicker_difficulty_easy,
                GrimorioLang.listpicker_difficulty_medium,
                GrimorioLang.listpicker_difficulty_hard };
        }

        // Tap per far partire il task
        private void recipePhoto_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
        {
            photoChooserTask.PixelHeight = 300;
            photoChooserTask.PixelWidth = 400;
            photoChooserTask.Show();
        }

        // Completo il task: la foto è prima fatta visualizzare al posto del segnaposto, poi salvata tramite stream nell'isostore.
        public void photoChooserTask_completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                BitmapImage image = new BitmapImage();
                image.SetSource(e.ChosenPhoto);
                recipePhoto.Source = image;
                DateTime now = DateTime.Now;
                photoNameOfRecipe = now.Millisecond.ToString() + now.Hour.ToString() + now.Minute.ToString() + now.Second.ToString();

                WriteableBitmap writeableImage = new WriteableBitmap(image);

                using (IsolatedStorageFile myIsoStore = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (!myIsoStore.DirectoryExists("RecipePhotos"))
                        myIsoStore.CreateDirectory("RecipePhotos");
                    IsolatedStorageFileStream fileStream = myIsoStore.CreateFile("/RecipePhotos/" + photoNameOfRecipe);
                    Extensions.SaveJpeg(writeableImage, fileStream, writeableImage.PixelWidth, writeableImage.PixelHeight, 0, 100);
                    fileStream.Close();
                }
            }
        }

        private void ApplicationBarInitializer()
        {
            ApplicationBar = new ApplicationBar();
            ApplicationBar.Mode = ApplicationBarMode.Default;
            ApplicationBar.Opacity = 1.0;
            ApplicationBar.IsVisible = true;
            ApplicationBar.IsMenuEnabled = false;

            // save button
            ApplicationBarIconButton btn_save = new ApplicationBarIconButton();
            btn_save.IconUri = new Uri("/Img/appbar_save.png", UriKind.Relative);
            btn_save.Text = GrimorioLang.save;
            ApplicationBar.Buttons.Add(btn_save);
            btn_save.Click += new EventHandler(btn_save_Click);

            // undo button
            ApplicationBarIconButton btn_undo = new ApplicationBarIconButton();
            btn_undo.IconUri = new Uri("/Img/appbar_cancel.png", UriKind.Relative);
            btn_undo.Text = GrimorioLang.undo;
            ApplicationBar.Buttons.Add(btn_undo);
            btn_undo.Click += new EventHandler(btn_undo_Click);
        }

        private void btn_undo_Click(object sender, EventArgs e)
        {
            List<RecipeIngredients> undoChangesRecipeIngredients = App.ViewModel.recipeIngredientsOfSelectedRecipe(App.ViewModel.getIdRecipeWithDefaultName());

            foreach (RecipeIngredients item in undoChangesRecipeIngredients)
            {
                App.ViewModel.DeleteRecipeToIng(item);
            }

            App.ViewModel.DeleteRecipe(App.ViewModel.getRecipeWithSelectedId(App.ViewModel.getIdRecipeWithDefaultName()));

            NavigationService.GoBack();

        }

        // Intercetto il tasto back per non lasciare il database "sporco di dati temporanei"
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            List<RecipeIngredients> undoChangesRecipeIngredients = App.ViewModel.recipeIngredientsOfSelectedRecipe(App.ViewModel.getIdRecipeWithDefaultName());

            foreach (RecipeIngredients item in undoChangesRecipeIngredients)
            {
                App.ViewModel.DeleteRecipeToIng(item);
            }

            App.ViewModel.DeleteRecipe(App.ViewModel.getRecipeWithSelectedId(App.ViewModel.getIdRecipeWithDefaultName()));

            NavigationService.GoBack();

            base.OnBackKeyPress(e);
        }


        // Quando salvo sostituisco la ricetta creata con il nome temporaneo e vado indietro (Arrivando alla home il db viene informato di salvare le modifiche)
        private void btn_save_Click(object sender, EventArgs e)
        {
            // Edit the properties inside that element
            DataRecipe recipeToEdit = App.ViewModel.getRecipeWithSelectedId(App.ViewModel.getIdRecipeWithDefaultName());

            if (recipeName.Text == "")
                MessageBox.Show(GrimorioLang.messagebox_nameRequired, GrimorioLang.messagebox_warning, MessageBoxButton.OK);
            else
            {
                bool sameName = false;
                foreach (DataRecipe dr in App.ViewModel.AllRecipes)
                    if (recipeName.Text.ToLower() == dr.RecipeName.ToLower())
                        sameName = true;
                if (sameName)
                    MessageBox.Show(GrimorioLang.messagebox_nameRequired, GrimorioLang.messagebox_warning, MessageBoxButton.OK);
                else
                {
                    recipeToEdit.RecipeName = recipeName.Text;
                    if (ratingStars.Value != 0.0)
                        recipeToEdit.Rating = ratingStars.Value;
                    if (recipeNumberOfPeople.Text != "")
                        recipeToEdit.NumberOfPeople = Convert.ToInt16(recipeNumberOfPeople.Text);
                    recipeToEdit.IsVegetarian = (bool)reciepVegetarian.IsChecked;
                    recipeToEdit.Difficulty = (string)recipeDifficultyListPicker.SelectedItem;
                    recipeToEdit.TimeForPreparation = recipeTime.Text;
                    recipeToEdit.Description = recipeBreifDescription.Text;
                    recipeToEdit.Matchings = recipeMatchings.Text;
                    recipeToEdit.Preparation = recipePreparation.Text;
                    recipeToEdit.Image = photoNameOfRecipe;
                    recipeToEdit.Dish = (string)recipeDishListPicker.SelectedItem;

                    NavigationService.GoBack();
                }
            }
        }

        private void AddQIng_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/AddQIng.xaml", UriKind.Relative));
        }

        // Caricamento della lista quando viene caricata la pagina.
        private void PivotItem_Loaded(object sender, RoutedEventArgs e)
        {
            List<GrimorioApplication.ViewModel.IngredientsAndQuantity> listOfIngredientsAndQuantity = App.ViewModel.getIngredientsAndQuantityOfRecipeSelected(App.ViewModel.getIdRecipeWithDefaultName());
            //IgredientsList.ItemsSource = listOfIngredientsAndQuantity;
            IgredientsList.ItemsSource = listOfIngredientsAndQuantity;
        }


        // Aggiunta di una ricetta temporanea al database.
        private void AddTemporaryRecipe()
        {
            DataRecipe temporaryRecipe = new DataRecipe()
            {
                RecipeName = "Grimorio_TeMpOrArY_Recipe",
                IsVegetarian = false,
                Rating = 3.0,
                NumberOfPeople = 2,
                Difficulty = "medium",
                Matchings = "",
                Description = "",
                Image = "",
                Dish = "Primo",
                TimeForPreparation = "40 min",
            };
            App.ViewModel.AddRecipe(temporaryRecipe);
        }

        private void DeleteIngredientFromList(object sender, System.Windows.Input.GestureEventArgs e)
        {
            // Prendo il nome dell'ingrediente.
            // dal nome risalgo all'id
            // Elimino la referenza se RecipeIngredient è uguale a recipe withdefaultname && idOfingredient
            List<RecipeIngredients> myList = App.ViewModel.recipeIngredientsOfSelectedRecipe(App.ViewModel.getIdRecipeWithDefaultName());
            GrimorioApplication.ViewModel.IngredientsAndQuantity toBeDel = (GrimorioApplication.ViewModel.IngredientsAndQuantity)IgredientsList.SelectedItem;
            
            foreach (RecipeIngredients item in myList)
            {
                if (item.Ingredient.IngredientName == toBeDel.ingredientName)
                {
                    App.ViewModel.DeleteRecipeToIng(item);
                }
            }

            // Reload list
            List<GrimorioApplication.ViewModel.IngredientsAndQuantity> listOfIngredientsAndQuantity = App.ViewModel.getIngredientsAndQuantityOfRecipeSelected(App.ViewModel.getIdRecipeWithDefaultName());

            IgredientsList.ItemsSource = listOfIngredientsAndQuantity;

        }

    }
}
